//
// rein.js
// Remote-Learner.net eLearning Interactions Library
// Amy Groshek of Remote-Learner.net
// 2011.10.03
//
;(function($) {
        //console.log('rein');
    $(document).ready( function() {
    // Accessory functions
      function is_touch_device() {// Return true if touch events supported
        return !!('ontouchstart' in window);
      }
        //
        // rotator
        // Rotates a set of images at a set time span in a set duration
        //
        $.fn.rotator = function(options) {
            //console.log('$.fn.rotator');
            var $this = $(this);

            // Options from defaults and passed
            var opts = $.extend({}, $.fn.rotator.defaults, options);

            // Hide all but the first image <div>
            $this.children(':eq(0)').siblings().hide();

            // Counter for which image is visible
            var ind = 0;

            // Fade elements in and out
            function doFadeOut() {
                //console.log('doFadeOut called');
                var fDur = opts.fadeDuration;
                var len = $this.children().length;
                var current = $this.children(':eq(' + ind + ')');
                // If index is at highest number, return to 0, else increment
                if ((ind + 1) === len) {
                    //console.log('last one reached');
                    // Fade visible image out, reset ind, fade new in
                    //$this.children(':eq(' + ind + ')').fadeOut(fDur);
                    ind = 0;
                    //$this.children(':eq(' + ind + ')').fadeIn(fDur);

                } else {
                    // Fade visible image out, increment ind, fade new in
                    //$this.children(':eq(' + ind + ')').fadeOut(fDur);
                    ind++;
                    //$this.children(':eq(' + ind + ')').fadeIn(fDur);
                }
                var next = $this.children(':eq(' + ind + ')');

                current.fadeOut(fDur);
                next.fadeIn(fDur);

            }

            function startInterval() {
                // console.log('interval started');
                var fInt = opts.fadeInterval;
//                $.fn.rotator.interval = setInterval(doFadeOut, opts.fadeInterval);
                $.fn.rotator.interval = setInterval(doFadeOut, fInt);
            }

            // Mouseover image stops interval
            $(this).hover(
                // Stop the timer
                function() {
                    //console.log('hover');
                    clearInterval($.fn.rotator.interval);
                },
                // Start the timer again when hover is left
                function() {
                    startInterval();
                }
            );



            // Start the rotation
            startInterval();

        };

        $.fn.rotator.defaults = {
            fadeDuration: 1000,
            fadeInterval: 2000
        };

        //
        // End rotator
        //
        //
        // onedrag
        // One-item drag and drop
        //
        $.fn.onedrag = function(options) {
            //console.log('onedrag');
            var $this = $(this);
            var opts = $.extend({}, $.fn.onedrag.defaults, options);
            var oneDrag = {};// obj to contain some variables and functions
            oneDrag.answerIsCorr = false;
            $this.find('.checkBtn').button({disabled:true});
            // Add draggable funct
            $this.find('.draggable').draggable({
                    drag: function() {
                        oneDrag.answIsCorr = false;
                    }
                });// end draggable init
            // Add droppable funct
            $this.find(".droppable").droppable({
                    activeClass: 'ui-state-active',
                    hoverClass: 'ui-state-highlight',
                    drop: function(event, ui) {
                        $this = $(this);
                        //console.log('drop');
                        $this.addClass('ui-state-disabled');
                        // If the id of the draggable matches the name of the correct item in the correct array
                        if ($this.hasClass('corr01')) {
                            // Draggable was dropped into the correct target, so we set its array val to true
                            oneDrag.answIsCorr = true;
                        }
                        else {
                            // Draggable was dropped into the incorrect target, so we set its array val to false
                            oneDrag.answIsCorr = false;
                        }
                        $this.parents('.oneDrag').find('.checkBtn').button({disabled:false});
                        //console.log('drop end of code');
                    },// end drop
                    out: function(event, ui) {
                        $this = $(this);
                        $this.removeClass('ui-state-disabled');
                        oneDrag.answIsCorr = false;
                        $this.parents('.oneDrag').find('.checkBtn').button({disabled:true});
                    }// end out
                });// end droppable inits

            // Generate dialogs
            oneDrag.posRemediation = $this.find('.remediation.positive').dialog({
                    modal: true,
                    autoOpen: false,
                    buttons: {
                        "Ok": function() {
                            $(this).dialog("close");
                        }
                    }
                });// end pos remediation dialog init

            oneDrag.negRemediation = $this.find('.remediation.negative').dialog({
                    modal: true,
                    autoOpen: false,
                    buttons: {
                        "Ok": function() {
                            $(this).dialog("close");
                        }
                    }
                });// end neg remediation dialog init

            // .checkBtn functionality
            $this.find(".checkBtn").click(function(e) {
                    if (oneDrag.answIsCorr === true) {
                        oneDrag.posRemediation.dialog('open');
                    }
                    else {
                        oneDrag.negRemediation.dialog('open');
                    }
                });// end .checkBtn click funct

        };// end $.fn.onedrag()

        $.fn.onedrag.defaults = {};
        //
        // End one-item drag and drop
        //

        //
        // Click hotspot
        //
        $.fn.clickhotspot = function(options) {
            //console.log('click hotspot');
            var $this = $(this);
            var opts = $.extend({}, $.fn.clickhotspot.defaults, options);
            // Get the offset of the stage parent div
            // Position target
            function positionTarg(){
                //console.log('positionTarg');
                var offset = $this.children('.clickStage').offset();// Get offset of stage (visible viable target) 

                $this.children('.clickTarg').css( 'position', 'absolute').offset({// set offset of the correct area (invisible laid over visible target) 
                        left: offset.left + Number( $this.find('.clickTarg .xcoord').html() ),
                        top: offset.top + Number( $this.find('.clickTarg .ycoord').html() )
                    });
            }
            positionTarg();

            // Reposition the click target any time the window is resized.
            $(window).resize( function() {
                    //console.log('window resize');
                    positionTarg();
                });

            var posDialog = $this.find('.remediation.positive').dialog({
                    autoOpen: false,
                    modal: true,
                    buttons: {
                        'Ok': function() {
                            $(this).dialog('close');
                        }
                    }
                });
            var negDialog = $this.find('.remediation.negative').dialog({
                    autoOpen: false,
                    modal: true,
                    buttons: {
                        "Ok": function() {
                            $(this).dialog("close");
                        }
                    }
                });

            // When the click target is clicked, show remediation
            $this.find('.clickTarg').click(function(e) {
                    //console.log('click on target');
                    posDialog.dialog('open');

                });

            // When the click target is clicked, show remediation
            $this.find('.clickStage').click(function(e) {
                    //console.log('click on stage');
                    negDialog.dialog('open');
                });

        };// end $.fn.clickhotspot

        $.fn.clickhotspot.defaults = {};
        //
        // End click hotspot
        //

        //
        // Drag and drop sorting
        //
        $.fn.draganddropsorting = function(options) {
            //console.log('$.fn.draganddropsorting');
            var $this = $(this);
            var opts = $.extend({}, $.fn.draganddropsorting.defaults, options);
            // Variable to track whether all answers are correct
            var allCorrect = false;
            var remShown = false;
            // Sortable functionality
            $this.find(".sortable").sortable({
                    connectWith: 'ul',
                    placeholder: 'ui-state-highlight',
                    dropOnEmpty: true
                });
            // Create dialogs for the pos and neg remediation
            var posDialog = $this.find('.remediation.positive').dialog({
                    autoOpen: false,
                    modal: true,
                    buttons: {
                        'Ok': function() {
                            $(this).dialog('close');
                        }
                    }
                });
            var negDialog = $this.find('.remediation.negative').dialog({
                    autoOpen: false,
                    modal: true,
                    buttons: {
                        "Ok": function() {
                            $(this).dialog("close");
                        }
                    }
                });
            // Show remediation
            function showRemediation() {
                if ( remShown === false ) {
                    //console.log( 'allCorrect is '+allCorrect );
                    if (allCorrect === true) {
                        posDialog.dialog('open');
                    } else {
                        negDialog.dialog('open');
                    }
                    remShown = true;
                }
            }
            // Function to check answers
            function checkAnswers() {
                allCorrect = true;
                // Run a loop to check to see that all items belong in their column
                for (var x = 0; x < $this.find('li').length; x++) {
                    //console.log('for loop, x = ' + x);
                    var $item = $this.find('li:eq(' + x + ')');
                    $item.removeClass('ui-icon-arrow-4');
                    // If the item has the class which matches the container ID show correct remediation
                    if ($item.hasClass('belongs-in-' + $item.parent().attr('id'))) {
                        //console.log($item.html() + ' is in the right column')
                        $item.addClass('ui-state-highlight');
                        $item.find('span').addClass('ui-icon-lightbulb');
                    }
                    else {
                        //console.log($item.html() + ' is in the wrong column')
                        $item.find('span.ui-icon-lightbulb').removeClass('ui-icon-lightbulb');
                        $item.find('span').addClass('ui-icon-closethick');
                        allCorrect = false;
                    }// end if/else

                }// end for loop

                $this.find('.sortable').animate({
                        opacity: '100'
                    },
                    500, '', showRemediation);
            }// end function checkAnswers()

            // Check Answers button click
            $this.find('button.checkAnswers').click(function() {
                    //console.log('checkBtn');
                    remShown = false;
                    $this.find('.sortable').animate({
                            opacity: '0'
                        },
                        500, '', checkAnswers);
                });// end check answer button click

        };// end $.fn.draganddropsorting

        $.fn.draganddropsorting.defaults = {};
        //
        // End drag and drop sorting
        //

        //
        //  domultidrop
        //  multi-item drag and drop into large circle
        //
        $.fn.domultidrop = function(options) {
            // This activity presents a circle droppable target.
            // Draggables are dropped inside the target.
            // Remediation in the form of light bulb or
            // X icon is shown in a fashion similar to that of
            // the multi-drag sorting activity.

            //console.log('$.fn.domultidrop');
            var $this = $(this);
            var opts = $.extend({}, $.fn.domultidrop.defaults, options);

            function removeClasses($el) {// Remove color classes from passed element

                if ($el.hasClass('drop-ok')) {
                    $el.removeClass('ui-state-highlight');
                    $el.find('span').removeClass('ui-icon-lightbulb').addClass('ui-icon-arrow-4');
                } else {
                    $el.find('span').removeClass('ui-icon-closethick').addClass('ui-icon-arrow-4');
                }
            }// end removeClasses()

            function fadeBack($el) {// Fade element opacity back
                //console.log('fadeBack');
                $el.fadeTo(400, 1);
            }// end fadeBack()

            function checkContents($el) {// Apply remediation colors, then call funct to fade opacity back
                if ($el.hasClass('drop-ok')) {
                    $el.addClass('ui-state-highlight');
                    $el.find('span').removeClass('ui-icon-arrow-4').addClass('ui-icon-lightbulb');
                } else {
                    $el.find('span').removeClass('ui-icon-arrow-4').addClass('ui-icon-closethick');
                }// end if/else

                fadeBack($el);

            }// end checkContents()

            $this.find('.sm-draggable').draggable();// Add draggable funct to draggables
            $this.find('.big-droppable').droppable({// Add droppable funct to drop target
                    //hoverClass: "ui-state-active",
                    drop: function(event, ui) {
                        //console.log('drop');
                        var $el = $(ui.draggable);
                        $el.addClass('is-in-droppable').fadeTo(400, 0.1,
                            function() {
                                removeClasses($el);// Remove any classes on droppable
                                checkContents($el); // Check element and assign remediation color
                            });
                    },
                    out: function(event, ui) {
                        //console.log('out');
                        var $el = $(ui.draggable);
                        $el.removeClass('is-in-droppable').fadeTo(400, 0.1,
                            function() {
                                removeClasses($el);// Remove any classes on the droppable
                                fadeBack($el);
                            });

                    }
                });// end droppable init

        };// end $.fn.domultidrop

        $.fn.domultidrop.defaults = {};
        //
        // end domultidrop
        //

        //
        //  dostepwise
        //  Stepwise process with animated pop-ups
        //
        $.fn.dostepwise = function(options) {
            //console.log('$.fn.dostepwise');
            var $this = $(this);
            var opts = $.extend({}, $.fn.dostepwise.defaults, options);
            var dostepwiseDialogArr = [];
            $this.find('.arrow').each( function(index, element) {
                    var paper = Raphael(element, 100, 60);
                    paper.path('M 30 10 L 30 30 L 10 30 L 50 50 L 90 30 L 70 30 L 70 10 Z').attr({
                            fill: 'gray',
                            stroke: 'black',
                            'stroke-linecap': 'round',
                            'stroke-width': 5,
                            'stroke-linejoin': 'round'
                        });
                });

            // init dialogs for each step
            $this.find('.step-detail').each( function(index, element) {

                    var $el = $(element);

                    dostepwiseDialogArr[index] = $el.dialog({
                            autoOpen: false,
                            modal: true,
                            buttons: {
                                'Ok': function() {
                                    $(this).dialog('close');
                                }
                            },
                            title: $el.siblings('.step-title').html(),
                            width: $el.css('width'),
                            show: 'blind',
                            hide: 'blind'
                        });
                });// end dialog inits

            // Click funct for each step (launches dialog)
            $this.find('.step').click( function(e) {
                    var $this = $(this);
                    var targetIndex = $this.parent().find('.step').index( $this );
                    //console.log( targetIndex );
                    dostepwiseDialogArr[ targetIndex ].dialog('open');
                });// end click funct init

        };// end $.fn.dostepwise
        $.fn.dostepwise.defaults = {};
        //
        // end dostepwise
        //

        //
        //  dosequential
        //  Sequential animation
        //
        $.fn.dosequential = function(options) {
            //console.log('$.fn.dosequential');
            var opts = $.extend({}, $.fn.dosequential.defaults, options);
            var $this = $(this);
            //console.log( $this );
            // Set bg and bg size for the parent element of the divs
            var $bgimg = $this.find('img.sequential-bg');
            // css to make bgimage the background of the content area
            $this.find('.sequential-cont').css({
                    'background': 'url(' + $bgimg.attr('src') + ')',
                    'background-size': $bgimg.attr('width') + 'px ' + $bgimg.attr('height') + 'px',
                    '-moz-background-size': $bgimg.attr('width') + 'px ' + $bgimg.attr('height') + 'px'
                });// end add bg to click target stack

            // Create dialogs
            var dialogArray = [];
            $this.find('div.item-details').each( function(index, element) {
                    dialogArray[index] = $(element).dialog({
                            autoOpen: false,
                            modal: true,
                            dialogClass: 'sequential-dialog',
                            width: '80%',
                            buttons: {
                                'Ok': function() {
                                    $(this).dialog('close');
                                }
                            }
                        });
                });// end create dialogs

            // Add click event to items and display each one in sequence
            $this.find('div.sequential-item').each(function(index, element) {
                    var $el = $(element);
                    $el.click(function(e) {
                            //console.log( index );
                            dialogArray[index].dialog('open');
                        });

                    $el.delay(2000 * index).show('blind', 1000);

                });// end click event init

        };// end $.fn.dosequential

        $.fn.dosequential.defaults = {};
        //
        // End dosequential
        //

        //
        // Markit
        //
        $.fn.markit = function(options) {
            //console.log('$.fn.markit');
            var opts = $.extend({}, $.fn.markit.defaults, options);
            var $this = $(this);
            //console.log( $this );

            $this[0].ontouchmove = function(e){ e.preventDefault(); };// Prevents ipad touch from scrolling page, so drag can be captured

            var width = $this.css('width');
            width = width.replace('px','');
            width = Number( width );

            var height = $this.css('height');
            height = height.replace('px','');
            height = Number( height );

            var g_masterPaper = Raphael($this[0], width, height); // Create raphael paper
            var masterBackground = g_masterPaper.rect(0,0,width,height); // Draw rectangle inside raph paper
            masterBackground.attr("fill", "#000000");// Background color of drawing rectangle
            masterBackground.attr("fill-opacity",0);// Opacity of this bgcolor
            masterBackground.attr("stroke","#000000");// Opacity of this bgcolor
            masterBackground.attr('stroke-opacity',0);// Turn off rectangle border. We will give this to the svg in the css.

            var loadSet = g_masterPaper.set();// Set for items drawn on load of page
            var drawSet = g_masterPaper.set(); // Set for items drawn by drag interaction

            masterBackground.mousemove( function(event) {
                    //console.log('mousemove');
                    var evt = event;
                    var IE = document.all?true:false;
                    var x, y;
                    if (IE) {
                        x = evt.clientX + document.body.scrollLeft +
                            document.documentElement.scrollLeft;
                        y = evt.clientY + document.body.scrollTop +
                            document.documentElement.scrollTop;
                    }
                    else {
                        x = evt.pageX;
                        y = evt.pageY;
                    }
                    // subtract paper coords on page
                    var paperOffset = $this.offset();// get paper x and paper y
                    this.ox = x - paperOffset.left;
                    this.oy = y - paperOffset.top;
                });

            var g_masterDrawingBox;

            var start = function () {// Drag event starts
                //console.log('start');
                g_masterPathArray = new Array();// Array for drawn path
                toggleDisabled($objsForToggleDisabled );// Enable undo and clear btns
            },
            move = function (dx, dy) {// Drag event mousemove
                //console.log('move');
                if (g_masterPathArray.length == 0) {
                    g_masterPathArray[0] = ["M",this.ox,this.oy];
                    g_masterDrawingBox = g_masterPaper.path(g_masterPathArray);
                    g_masterDrawingBox.attr({ 
                            'stroke': opts.utensils[opts.utensilIndex].stroke,
                            'stroke-width': opts.utensils[opts.utensilIndex].strokeWidth,
                            'stroke-opacity': opts.utensils[opts.utensilIndex].strokeOpacity,
                            'stroke-linecap':'round',
                            'stroke-linejoin':'round'
                        });    
                    //console.log( drawSet.items );
                }
                else {
                    g_masterPathArray[g_masterPathArray.length] =["L",this.ox,this.oy];
                    g_masterDrawingBox.attr({path: g_masterPathArray});
                    //console.log( drawSet.items ); 
                }
            },
            up = function () {// Drag event ends
                drawSet.push(g_masterDrawingBox);// Put assembled path object into drawSet for later access
                //console.log( drawSet );
            };

            masterBackground.drag(move, start, up);

            // 
            //  MARKIT BUTTONS  
            //

            var clearUndoBtns = $('.markit-controls .undo-btn, .markit-controls .clear-btn');// obj for undo and clear class management

            function usePen(obj) {
                //console.log('usePen');
                opts.utensilIndex = 0;// Change the current markit cursor to the pen
                $(obj).toggleClass('selected').siblings('.use-highlight-btn').toggleClass('selected');// remove highlight class from highligher, add to pen
                $this.find('svg').css('cursor','url('+M.cfg.wwwroot+'/theme/idstandard/pix/pencil-flip.png), pointer');// update svg css cursor

            }// End use pen

            function useHighlight(obj) {
                //console.log('useHighlight');
                opts.utensilIndex = 1;// Change the current markit cursor to the highlight
                $(obj).toggleClass('selected').siblings('.use-pen-btn').toggleClass('selected');// remove highlight class from pen btn, add to highlight
                $this.find('svg').css('cursor','url('+M.cfg.wwwroot+'/theme/idstandard/pix/highlight-flip.png), pointer');// Change css cursor to higlight marker 

            }// End use highlight


            var $objsForToggleDisabled = $('.markit-controls .undo-btn, .markit-controls .clear-btn'); // Declare here so we reduce number of queries
            function toggleDisabled(objs) {
                // toggles disabled state for both undo and clear buttons 
                // used when clear btn is selected, and when a draw event occurs
                //console.log('toggleDisabled()');
                if ($(objs).hasClass('disabled')){

                    $(objs).removeClass('disabled');
                }
            }// End toggleDisabled()

            function clearMarkit() {
                //console.log('clearMarkit()');

                if ( !$objsForToggleDisabled.hasClass('disabled') ) {
                    var i = drawSet.items.length - 1;
                    for (i;i>-1;i--) {
                        //console.log('index is '+i);

                        drawSet.items[i].remove();// Remove element from paper
                        drawSet.items.splice(i,1);// Clean up arrays
                        drawSet.splice(i,1);

                    }
                }
                $objsForToggleDisabled.addClass('disabled');
            }// End clearMarkit()

            // TODO: There is a very difficult to replicate bug in clearMarkit(), seemingly related with mutiple drawn paths, use of both utensils, and the selection of undo several times in a row very quickly... 

            function undoMarkit() {
                //console.log('undoMarkit()');

                if ( !$objsForToggleDisabled.hasClass('disabled') ) {
                    var i = drawSet.items.length - 1;
                    //console.log('index is '+i);
                    drawSet.items[i].remove();// Remove element from paper
                    drawSet.items.splice(i,1);// Clean up arrays
                    drawSet.splice(i,1);
                }

                if (drawSet.items.length === 0) {
                    $objsForToggleDisabled.addClass('disabled');
                }
            }// End undoMarkit()


            $('.markit-controls .use-highlight-btn').click( function(e) { // Highlight button click listener
                    //console.log('highlight selected');
                    var $this = $(this);
                    //console.log($this);
                    useHighlight($this);

                });// End highlight click listener

            $('.markit-controls .use-pen-btn').click( function(e) { // Pen button click listener
                    //console.log('highlight selected');
                    var $this = $(this);
                    //console.log($this);
                    usePen($this);

                });// End pen click listener

            $('.markit-controls .clear-btn').click( function(e) { // Pen button click listener
                    //console.log('clear btn selected');
                    clearMarkit();
                });// End pen click listener


            $('.markit-controls .undo-btn').click( function(e) { // Pen button click listener
                    //console.log('clear btn selected');
                    undoMarkit();
                });// End pen click listener

            $('.markit-controls .control').button();// skin markit controls 

            //
            // END MARKIT CONTROLS
            //

            //
            // DRAW IMAGES, LINES, AND ___ FROM MARKUP
            //
            function drawOnLoad(){
                function drawImage(el){
                    //console.log('drawImage');
                    var $el = $(el);
                    // The following check that required and optional values exist. If none are supplied, a default value is applied.
                    var imgSrc = $el.children('.src').html();
                    var imgSrcReturn = ( imgSrc && imgSrc.length >= 1 )?String(imgSrc):alert('Image src not specified.');// alert rather than default value. We cannot proceed without an img src

                    var imgX = $el.children('.x').html();
                    var imgXReturn = (imgX && imgX.length >= 1)?Number(imgX):0;

                    var imgY = $el.children('.y').html();
                    var imgYReturn = (imgY && imgY.length >= 1 )?Number(imgY):0;

                    var imgWidth = $el.children('.width').html();
                    var imgWidthReturn = (imgWidth && imgWidth.length >= 1)?Number(imgWidth):200;

                    var imgHeight = $el.children('.height').html();
                    var imgHeightReturn = (imgHeight && imgHeight.length >= 1)?Number(imgHeight):200;

                    var image = g_masterPaper.image( imgSrcReturn, imgXReturn, imgYReturn, imgWidthReturn, imgHeightReturn );
                    loadSet.push( image );
                }

                // Draw any draw-on-load images 
                $this.find('.draw-on-load .draw-image').each( function(i,el){
                        drawImage(el);
                    });// End draw image

                function drawLine(el) {
                    //console.log('drawLine()');
                    var $el = $(el);
                    // The following check that required and optional values exist. If none are supplied, a default value is applied.
                    var startx = $el.children('.startx').html();
                    var startxReturn = ( startx && startx.length >= 1 )?Number( startx ):0;

                    var starty = $el.children('.starty').html(); 
                    var startyReturn = ( starty && starty.length >= 1 )?Number( starty ):100;

                    var stopx = $el.children('.stopx').html();
                    var stopxReturn = ( stopx && stopx.length >= 1 )?Number( stopx ):200;

                    var stopy = $el.children('.stopy').html();
                    var stopyReturn = ( stopy && stopy.length >= 1 )?Number( stopy ):100;

                    var strokeWidth = $el.children('.stroke-width').html(); 
                    var strokeWidthReturn = ( strokeWidth && strokeWidth.length >= 1 )?Number( strokeWidth ):5;

                    var stroke = $el.children('.stroke').html();// Color of the stroke
                    var strokeReturn = ( stroke && stroke.length >= 1 ) ? String( stroke ) : '#000';

                    var strokeOpacity = $el.children('.stroke-opacity').html();
                    var strokeOpacityReturn = ( strokeOpacity && strokeOpacity.length >= 1 ) ? Number( strokeOpacity ):1;

                    // TODO: note this difference from pw sketchpad when adapting documentation
                    //var strokeLinecap = element.children('.stroke-linecap').html();
                    //var strokeLinecapReturn = ( element.children('.stroke-linecap').html() && element.children('.stroke-linecap').html().length >= 1 )?String( element.children('.stroke-linecap').html() ):'round';

                    var line = g_masterPaper.path('M'+startxReturn+','+startyReturn+' L'+stopxReturn+','+stopyReturn ).attr({
                            'stroke-width': strokeWidthReturn,
                            'stroke': strokeReturn,
                            'stroke-opacity': strokeOpacityReturn,
                            'stroke-linecap': 'round'
                        });
                    loadSet.push( line );
                }

                // Draw line
                $this.find('.draw-on-load .draw-line').each( function(i,el){
                        drawLine(el);
                    });// End draw line

                function drawText(el){
                    //console.log( 'drawText()');
                    var $el = $(el);
                    // The following check that required and optional values exist. If none are supplied, a default value is applied.
                    var txt = $el.children('.text').html();
                    var txtRet = ( txt && txt.length >= 1 ) ? String( txt ) : 'Text string not provided!';// No sense going on without this value

                    var x = $el.children('.x').html();
                    var xRet = ( x && x.length >= 1 ) ? Number( x ) : 100;

                    var y = $el.children('.y').html();
                    var yRet = ( y && y.length >= 1 ) ? Number( y ) : 100;

                    var fontFamily = $el.children('.font-family').html();
                    var fontFamilyRet = ( fontFamily && fontFamily.length >= 1 )?String( fontFamily ):'Helvetica, Arial, sans-serif';

                    var fontSize = $el.children('.font-size').html();
                    var fontSizeRet = ( fontSize && fontSize.length >= 1 )?Number( fontSize ):20;

                    var fill = $el.children('.fill').html();
                    var fillRet = ( fill && fill.length >= 1 )?String( fill ):'#000';

                    var opacity = $el.children('.opacity').html();
                    var opacityRet = (opacity && opacity.length >= 1 )?Number( opacity ):1;

                    var fontWeight = $el.children('.font-weight').html();
                    var fontWeightRet = ( fontWeight && fontWeight.length >= 1 )?String( fontWeight ):'bold';

                    var text = g_masterPaper.text( xRet, yRet, txtRet ).attr({
                            'font-family': fontFamilyRet,  
                            'fill': fillRet,  
                            'font-size': fontSizeRet,  
                            'font-weight': fontWeightRet,  
                            'opacity': opacityRet,
                            'text-anchor': 'start'
                        });
                    loadSet.push( text );
                }// End draw text


                // Draw text init
                $this.find('.draw-on-load .draw-text').each( function(i,el){
                        drawText(el);
                    });// End text init

                masterBackground.toFront();

            }// End drawOnLoad()

            drawOnLoad();

            //
            // END DRAW FROM MARKUP
            //


            return g_masterPaper;

        };

        $.fn.markit.defaults = {
            'utensils' : [
                {// Pen default settings
                    'stroke':'#000',
                    'strokeWidth': 3,
                    'strokeOpacity':1,
                    'cursor':function() { if (M) { return 'url('+M.cfg.wwwroot+'/theme/idstandard/pix/pencil-flip.png), auto;'; } }
                },
                {// Highlight default settings
                    'stroke':'#EDF30C',
                    'strokeWidth':10,
                    'strokeOpacity':0.5,
                    'cursor':function() { if (M) { return 'url('+M.cfg.wwwroot+'/theme/idstandard/pix/highlight-flip.png), auto;'; } }
                }
            ],
            'utensilIndex': 0
        };// End markit defaults

        //
        // End markit
        //

        //
        // jQuery UI tooltip
        //
        $.fn.dotip = function(options) {
            var opts = $.extend({}, $.fn.dotip.defaults, options);

            $('.tip-trigger').tooltip({
                items: "img, span, div, [title]",
                track: true,
                content: function() {
                    var $this = $(this);
                    // If .tip-trigger has a title attribute, use that for the tooltip.
                    if ($this.is( "[title]")) {
                        return $this.attr( "title" );
                    }
                    // If .tip-trigger is an img, use the alt for the tooltip.
                    if ($this.is("img")) {
                        return $this.attr("alt");
                    }
                    // If .tip-trigger is a span or div with no title attribute, use another element
                    // with a specified ID for the tooltip.
                    if ($this.is("span") || $this.is("div")) {
                        var sourceid = $this.attr('id');
                        var tipcontentid = '#tip-source-'+sourceid;
                        return $(tipcontentid).html();
                    }
                }
            });
        };

        $.fn.dotip.defaults = {};

        //
        // Inits for all plugins
        //

        // Button
        $('.doButton').button();

        // Accordion
        $('.doAccordion').accordion({
            heightStyle: 'fill'
        });

        // Tabs
        if ($('.doTabs').length >= 1) {
            //console.log('doTabs in page');
            var tabs = $('.doTabs').tabs();
            //console.log(tabs);
        }

        // Image rotator
        if ($('#rotator').length >= 1) {
            // If rotator element exists on the page, then do the following
            $('#rotator').rotator({
                    fadeInt: 2000
                });
        }

        // One-item drag and drop
        if ($('.oneDrag').length >= 1) {
            // If oneDrag exists on the page then do the following
            if (console.warn) { console.warn('One-item drag and drop is deprecated. You might want to try a different module.'); }
            $('.oneDrag').onedrag({});
        }

        // Click hotspot
        if ($('.clickHotspot').length >= 1) {
            $('.clickHotspot').clickhotspot({});
        }

        // Drag and drop column sorting
        if ($('.sortMultipleLists').length >= 1) {
            $('.sortMultipleLists').draganddropsorting({});
        }

        // domultidrop or 'bubble of safety'
        if ($('.do-multi-drop').length >= 1) {
            $('.do-multi-drop').domultidrop({});
        }

        // dostepwise
        if ($('.do-stepwise').length >= 1) {
            $('.do-stepwise').dostepwise({});
        }

        // dosequential
        if ($('.do-sequential').length >= 1) {
            $('.do-sequential').dosequential({});
        }

        // markit
        if ($('.markit').length >= 1) {
            $('.markit:eq(0)').markit({});
        }

        // tooltip
        if ($('.tip-trigger').length >= 1) {
            $('.tip-trigger').dotip({});
        }

    });

})(jQuery);
